// DOM元素加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (sessionStorage.getItem('isLoggedIn') !== 'true') {
        window.location.href = 'index.html';
        return;
    }

    // 显示欢迎信息
    const username = sessionStorage.getItem('username');
    if (username) {
        document.getElementById('welcomeUsername').textContent = username;
    }

    // 初始化导航
    initNavigation();
    
    // 初始化实验卡片点击事件
    initExperimentCards();
    
    // 初始化容器控制
    initContainerControl();
    
    // 初始化个人中心标签页
    initProfileTabs();
    
    // 初始化搜索功能
    initSearch();

    // 实验卡片点击事件
    const experimentCards = document.querySelectorAll('.experiment-card');
    experimentCards.forEach(card => {
        const enterButton = card.querySelector('.btn-enter');
        if (enterButton) {
            enterButton.addEventListener('click', function() {
                const experimentId = card.getAttribute('data-experiment-id');
                const title = card.querySelector('h3').textContent;
                const description = card.querySelector('.card-body p').textContent;
                
                // 更新模态框内容
                document.querySelector('.modal-title').textContent = title;
                document.getElementById('modal-description').textContent = description;
                
                // 重置容器状态
                const containerStatus = document.getElementById('containerStatus');
                const containerInfo = document.getElementById('containerInfo');
                if (containerStatus && containerInfo) {
                    containerStatus.textContent = '未启动';
                    containerStatus.className = 'status-value';
                    containerInfo.style.display = 'none';
                }
                
                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('experimentModal'));
                modal.show();
            });
        }
    });

    // 下载实验指导书
    const downloadGuide = document.getElementById('downloadGuide');
    if (downloadGuide) {
        downloadGuide.addEventListener('click', function(e) {
            e.preventDefault();
            // TODO: 实现下载功能
            alert('正在准备下载实验指导书...');
        });
    }

    // 复制容器地址
    const copyAddressBtn = document.getElementById('copyAddress');
    if (copyAddressBtn) {
        copyAddressBtn.addEventListener('click', function() {
            const address = document.getElementById('containerAddress').textContent;
            navigator.clipboard.writeText(address).then(() => {
                this.innerHTML = '<i class="fas fa-check"></i>';
                setTimeout(() => {
                    this.innerHTML = '<i class="fas fa-copy"></i>';
                }, 2000);
            });
        });
    }

    // 启动容器
    const startContainerBtn = document.getElementById('startContainer');
    const stopContainerBtn = document.getElementById('stopContainer');
    let containerTimer = null; // 用于存储计时器ID

    if (startContainerBtn && stopContainerBtn) {
        startContainerBtn.addEventListener('click', function() {
            const statusElement = document.getElementById('containerStatus');
            const containerInfo = document.getElementById('containerInfo');
            const containerAddress = document.getElementById('containerAddress');
            
            if (!statusElement || !containerInfo || !containerAddress) return;

            // 更新状态为启动中
            statusElement.textContent = '启动中...';
            statusElement.className = 'status-value pending';
            this.disabled = true;
            
            // 模拟API调用
            setTimeout(() => {
                // 模拟返回的容器地址
                const address = 'http://practice.example.com:' + Math.floor(Math.random() * 1000 + 8000);
                
                // 更新状态
                statusElement.textContent = '运行中';
                statusElement.className = 'status-value running';
                containerInfo.style.display = 'block';
                containerAddress.textContent = address;
                
                // 切换按钮显示
                this.style.display = 'none';
                stopContainerBtn.style.display = 'inline-flex';
                
                // 开始倒计时
                startTimer();
            }, 2000);
        });

        // 关闭容器事件
        stopContainerBtn.addEventListener('click', function() {
            const statusElement = document.getElementById('containerStatus');
            const containerInfo = document.getElementById('containerInfo');
            
            if (!statusElement || !containerInfo) return;

            // 确认是否关闭容器
            if (confirm('确定要关闭容器吗？这将终止当前实验环境。')) {
                // 更新状态为关闭中
                statusElement.textContent = '关闭中...';
                statusElement.className = 'status-value pending';
                this.disabled = true;

                // 模拟API调用
                setTimeout(() => {
                    // 更新状态
                    statusElement.textContent = '已停止';
                    statusElement.className = 'status-value stopped';
                    containerInfo.style.display = 'none';

                    // 切换按钮显示
                    this.style.display = 'none';
                    startContainerBtn.style.display = 'inline-flex';
                    startContainerBtn.disabled = false;

                    // 清除计时器
                    if (containerTimer) {
                        clearInterval(containerTimer);
                        containerTimer = null;
                    }
                }, 1500);
            }
        });
    }

    // 计时器功能
    function startTimer() {
        let timeLeft = 2 * 60 * 60; // 2小时（秒）
        const timerElement = document.getElementById('remainingTime');
        if (!timerElement) return;
        
        // 清除可能存在的旧计时器
        if (containerTimer) {
            clearInterval(containerTimer);
        }
        
        containerTimer = setInterval(() => {
            timeLeft--;
            const hours = Math.floor(timeLeft / 3600);
            const minutes = Math.floor((timeLeft % 3600) / 60);
            
            timerElement.textContent = `${hours}小时${minutes.toString().padStart(2, '0')}分`;
            
            if (timeLeft <= 0) {
                clearInterval(containerTimer);
                containerTimer = null;
                const containerStatus = document.getElementById('containerStatus');
                const containerInfo = document.getElementById('containerInfo');
                const startContainerBtn = document.getElementById('startContainer');
                const stopContainerBtn = document.getElementById('stopContainer');
                
                if (containerStatus && containerInfo && startContainerBtn && stopContainerBtn) {
                    containerStatus.textContent = '已停止';
                    containerStatus.className = 'status-value stopped';
                    containerInfo.style.display = 'none';
                    startContainerBtn.style.display = 'inline-flex';
                    startContainerBtn.disabled = false;
                    stopContainerBtn.style.display = 'none';
                }
            }
        }, 1000);
    }

    // 个人中心标签切换
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');

    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const target = this.getAttribute('data-target');
            
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            tabContents.forEach(content => {
                content.style.display = 'none';
                if (content.id === target) {
                    content.style.display = 'block';
                }
            });
        });
    });

    // 注销功能
    const logoutButton = document.querySelector('.logout');
    logoutButton.addEventListener('click', function(e) {
        e.preventDefault();
        if (confirm('确定要注销吗？')) {
            // 清除session存储
            sessionStorage.clear();
            // 重定向到登录页面
            window.location.href = 'index.html';
        }
    });

    // 实验开始按钮点击事件
    const startButtons = document.querySelectorAll('.btn-start');
    startButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation();
            const experimentId = this.getAttribute('data-experiment-id');
            // TODO: 实现实验启动逻辑
            console.log('Starting experiment:', experimentId);
        });
    });

    // 继续实验按钮点击事件
    const continueButtons = document.querySelectorAll('.btn-continue');
    continueButtons.forEach(button => {
        button.addEventListener('click', function() {
            const experimentId = this.getAttribute('data-experiment-id');
            // TODO: 实现继续实验逻辑
            console.log('Continuing experiment:', experimentId);
        });
    });

    // 页面加载时默认显示欢迎页面
    const welcomeLink = document.querySelector('[href="#welcome"]');
    if (welcomeLink) {
        welcomeLink.click();
    }
});

// 导航功能
function initNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    const sections = document.querySelectorAll('.content-section');
    
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            if (this.classList.contains('logout')) return;
            
            e.preventDefault();
            const target = this.getAttribute('href').substring(1);
            
            navItems.forEach(nav => nav.classList.remove('active'));
            this.classList.add('active');
            
            sections.forEach(section => {
                section.classList.remove('active');
                if (section.id === target) {
                    section.classList.add('active');
                }
            });
        });
    });
}

// 初始化实验卡片
function initExperimentCards() {
    const experimentModal = new bootstrap.Modal(document.getElementById('experimentModal'));
    const cards = document.querySelectorAll('.experiment-card');
    
    cards.forEach(card => {
        const enterButton = card.querySelector('.btn-enter');
        if (enterButton) {
            enterButton.addEventListener('click', function() {
                // 获取实验信息
                const experimentId = card.dataset.experimentId;
                const title = card.querySelector('h3').textContent;
                const description = card.querySelector('.card-body p').textContent;
                const duration = card.querySelector('.fa-clock').parentElement.textContent;
                const difficulty = card.querySelector('.fa-signal').parentElement.textContent;
                
                // 更新模态框内容
                document.getElementById('modalExperimentTitle').textContent = title;
                document.getElementById('modalExperimentDescription').textContent = description;
                document.getElementById('modalExperimentDuration').textContent = duration;
                document.getElementById('modalExperimentDifficulty').textContent = difficulty;
                document.getElementById('modalExperimentStudents').textContent = '36人学习';
                
                // 重置容器状态
                document.getElementById('containerStatus').textContent = '未启动';
                document.getElementById('containerStatus').className = 'status-value';
                document.getElementById('containerInfo').style.display = 'none';
                document.getElementById('containerAddress').style.display = 'none';
                document.getElementById('timerBox').style.display = 'none';
                document.getElementById('startContainer').style.display = '';
                document.getElementById('stopContainer').style.display = 'none';
                
                // 显示模态框
                experimentModal.show();
            });
        }
    });
}

// 初始化容器控制
function initContainerControl() {
    const startButton = document.getElementById('startContainer');
    const stopButton = document.getElementById('stopContainer');
    const containerStatus = document.getElementById('containerStatus');
    const containerInfo = document.getElementById('containerInfo');
    const containerAddress = document.getElementById('containerAddress');
    const containerUrl = document.getElementById('containerUrl');
    const timerBox = document.getElementById('timerBox');
    const timerDisplay = document.getElementById('containerTimer');
    let containerTimer;
    
    // 启动容器
    startButton.addEventListener('click', function() {
        // 更新状态为启动中
        containerStatus.textContent = '启动中...';
        containerStatus.className = 'status-value pending';
        startButton.disabled = true;
        containerInfo.style.display = 'block';
        
        // 模拟API调用延迟
        setTimeout(() => {
            containerStatus.textContent = '运行中';
            containerStatus.className = 'status-value running';
            containerAddress.style.display = 'flex';
            containerUrl.textContent = 'http://localhost:8080';
            timerBox.style.display = 'flex';
            startButton.style.display = 'none';
            stopButton.style.display = '';
            
            // 启动计时器
            startTimer();
        }, 2000);
    });
    
    // 停止容器
    stopButton.addEventListener('click', function() {
        if (confirm('确定要关闭容器吗？实验环境将被清除。')) {
            // 更新状态为关闭中
            containerStatus.textContent = '关闭中...';
            containerStatus.className = 'status-value pending';
            stopButton.disabled = true;
            
            // 模拟API调用延迟
            setTimeout(() => {
                containerStatus.textContent = '已停止';
                containerStatus.className = 'status-value stopped';
                containerAddress.style.display = 'none';
                timerBox.style.display = 'none';
                stopButton.style.display = 'none';
                startButton.style.display = '';
                startButton.disabled = false;
                
                // 停止计时器
                clearInterval(containerTimer);
            }, 1500);
        }
    });
    
    // 复制地址
    document.getElementById('copyAddress').addEventListener('click', function() {
        const url = containerUrl.textContent;
        navigator.clipboard.writeText(url).then(() => {
            alert('地址已复制到剪贴板');
        });
    });
    
    // 计时器功能
    function startTimer() {
        let timeLeft = 2 * 60 * 60; // 2小时
        
        function updateTimer() {
            const hours = Math.floor(timeLeft / 3600);
            const minutes = Math.floor((timeLeft % 3600) / 60);
            const seconds = timeLeft % 60;
            
            timerDisplay.textContent = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
            
            if (timeLeft === 0) {
                clearInterval(containerTimer);
                stopButton.click();
            } else {
                timeLeft--;
            }
        }
        
        updateTimer();
        containerTimer = setInterval(updateTimer, 1000);
    }
}

// 初始化个人中心标签页
function initProfileTabs() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content > div');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            tabBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            const target = this.textContent.toLowerCase().replace(/\s+/g, '-');
            tabContents.forEach(content => {
                content.classList.remove('active');
                if (content.classList.contains(target)) {
                    content.classList.add('active');
                }
            });
        });
    });
}

// 搜索功能
function initSearch() {
    const searchInput = document.getElementById('experiment-search');
    const searchBtn = document.getElementById('search-btn');
    
    if (searchInput && searchBtn) {
        searchBtn.addEventListener('click', function() {
            const searchTerm = searchInput.value.trim().toLowerCase();
            const cards = document.querySelectorAll('.experiment-card');
            
            cards.forEach(card => {
                const title = card.querySelector('h3').textContent.toLowerCase();
                const description = card.querySelector('.card-body p').textContent.toLowerCase();
                
                if (title.includes(searchTerm) || description.includes(searchTerm)) {
                    card.style.display = '';
                } else {
                    card.style.display = 'none';
                }
            });
        });
        
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchBtn.click();
            }
        });
    }
} 